<template>
    <div class="table-container" v-loading="loading" :element-loading-text="loadingText">
        <!-- <el-button v-loading.fullscreen.lock="fullscreenLoading" style="position: absolute; right: 0" v-print="printObj"
            type="primary">打印</el-button> -->
        <el-tabs type="border-card" style="min-width: 100% !important;" v-model="activeName">
            <el-tab-pane label="凉山州第一人民医院ICU疾病统计" name="disease">
                <div id="printTable">
                    <h2 style="text-align: center">凉山州第一人民医院ICU疾病统计</h2>
                    <div class="operate">
                        <div style=" margin-right: 20px">
                            <el-date-picker v-model="selectedYear" type="monthrange" format="YYYY-MM"
                                value-format="YYYY-MM" range-separator="至" start-placeholder="开始时间"
                                end-placeholder="结束时间" placeholder="请选择年份" :default-value="new Date()"
                                @clear="handleClear" style=" margin-right: 20px;width: 240px;">
                            </el-date-picker>
                            <el-button @click="handleYearChange">
                                统计
                            </el-button>
                        </div>

                        <el-button type="primary" @click="handleExportExcel">
                            导出数据
                        </el-button>
                    </div>

                    <table class="complex-table">
                        <!-- 第一行表头 -->
                        <thead class="header">
                            <tr>
                                <template v-for="(header, index) in headers" :key="index">
                                    <th v-if="!header.children && header.title !== 'MODS'"
                                        :rowspan="header.rowspan || 1" :colspan="header.colspan || 1">
                                        {{ header.title }}
                                    </th>
                                    <th v-else-if="header.title == 'MODS'" :rowspan="header.rowspan || 1"
                                        :colspan="header.colspan || 1">
                                        <div v-for="item in header.title.split('')">{{
                                            item }}</div>

                                    </th>
                                    <th v-else :colspan="header.colspan || 1" :rowspan="header.rowspan || 1">
                                        {{ header.title }}
                                    </th>
                                </template>
                            </tr>

                            <!-- 第二行表头 -->
                            <tr>
                                <template v-for="(header, index) in headers" :key="index">
                                    <template v-if="header.children">
                                        <template v-for="(child, childIndex) in header.children" :key="childIndex">
                                            <th :colspan="child.colspan || 1" v-if="child.title !== ''">
                                                {{ child.title }}
                                            </th>
                                        </template>
                                    </template>
                                </template>
                            </tr>

                            <!-- 第三行表头 -->
                            <tr style="font-size: 10px">
                                <template v-for="(header, index) in headers" :key="index">
                                    <template v-if="header.children">
                                        <template v-for="(child, childIndex) in header.children" :key="childIndex">
                                            <template v-for="(childItem, childIndex) in child.children"
                                                :key="childIndex">
                                                <th
                                                    v-if="childItem.title == 'AECOPD' || childItem.title == 'DIC' || childItem.title == 'HELLP综合征' || childItem.title == 'MODS'">
                                                    <div v-for="item in childItem.title.split('')">{{
                                                        item }}</div>

                                                </th>
                                                <th v-else>
                                                    {{ childItem.title }}
                                                </th>
                                            </template>
                                        </template>
                                    </template>
                                </template>
                            </tr>
                        </thead>

                        <!-- 表格内容 -->
                        <tbody>
                            <tr v-for="(item, rowIndex) in tableData" :key="rowIndex">
                                <td v-for="(value, key) in item" :key="key">
                                    <span>{{ value }}</span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </el-tab-pane>
            <el-tab-pane label="统计" name="second">
                <Statistics></Statistics>
            </el-tab-pane>
            <!-- <el-tab-pane label="凉山州第一人民医院ICU危重症患者APACHE II评分登记表" name="third">
                <apache></apache>
            </el-tab-pane> -->
        </el-tabs>

    </div>
</template>

<script setup>
import { onMounted, reactive, ref, toRefs } from "vue";
import { getDiseaseAPI } from "../api/book.js";
import { writeFile, utils } from "xlsx";
import Statistics from "./Statistics.vue";
import apache from "./apache.vue";
import * as XLSX from 'xlsx';
import dayjs from 'dayjs';
const activeName = ref("disease");
const headers = [
    {
        title: "系统",
        key: "system",
        children: [
            {
                title: "分类",
                key: "classification",
                children: [{ title: "疾病", key: "disease" }],
            },
        ],
    },
    {
        title: "神经系统疾病",
        key: "neuron",
        colspan: 16,
        children: [
            {
                title: "脑血管意外",
                key: "cerebrovascular",
                colspan: 3,
                children: [
                    { title: "脑出血", key: "cerebrovascular1" },
                    { title: "脑梗死", key: "cerebrovascular2" },
                    { title: "蛛网膜下腔出血", key: "cerebrovascular3" },
                ],
            },
            {
                title: "脑外科疾病",
                key: "brainSurgery",
                colspan: 9,
                children: [
                    { title: "脑挫裂伤", key: "brainSurgery1" },
                    { title: "弥漫性轴索损伤", key: "brainSurgery2" },
                    { title: "脑疝", key: "brainSurgery3" },
                    { title: "硬膜下出血", key: "brainSurgery4" },
                    { title: "硬膜外出血", key: "brainSurgery5" },
                    { title: "颅底骨折", key: "brainSurgery6" },
                    { title: "脑脊液耳鼻漏", key: "brainSurgery7" },
                    { title: "脑肿瘤", key: "brainSurgery8" },
                    { title: "脑血管瘤", key: "brainSurgery9" },
                ],
            },
            {
                title: "神经内科疾病",
                key: "neurology",
                colspan: 4,
                children: [
                    { title: "癫痫", key: "neurology1" },
                    { title: "颅内感染", key: "neurology2" },
                    { title: "格林巴利综合征", key: "neurology3" },
                    { title: "重症肌无力", key: "neurology4" },
                ],
            },
        ],
    },
    {
        title: "呼吸系统疾病",
        key: "breathe",
        colspan: 19,
        children: [
            {
                title: "胸外科疾病",
                key: "thoracicSurgery",
                colspan: 14,
                children: [
                    { title: "肋骨骨折", key: "thoracicSurgery1" },
                    { title: "肺挫伤", key: "thoracicSurgery2" },
                    { title: "胸腔积液", key: "thoracicSurgery3" },
                    { title: "气胸", key: "thoracicSurgery4" },
                    { title: "心包填塞", key: "thoracicSurgery5" },
                    { title: "心脏破裂", key: "thoracicSurgery6" },
                    { title: "气道异物", key: "thoracicSurgery7" },
                    { title: "先心病", key: "thoracicSurgery8" },
                    { title: "风心病", key: "thoracicSurgery9" },
                    { title: "肺癌", key: "thoracicSurgery10" },
                    { title: "食道癌", key: "thoracicSurgery11" },
                    { title: "纵膈肿瘤", key: "thoracicSurgery12" },
                    { title: "肺大泡", key: "thoracicSurgery13" },
                    { title: "脓胸", key: "thoracicSurgery14" },
                ],
            },
            {
                title: "呼吸内科疾病",
                key: "flow",
                colspan: 5,
                children: [
                    { title: "哮喘", key: "flow1" },
                    { title: "肺炎", key: "flow2" },
                    { title: "AECOPD", key: "flow3" },
                    { title: "肺栓塞", key: "flow3" },
                    { title: "急性喉炎", key: "flow3" },
                ],
            },
        ],
    },
    {
        title: "消化系统疾病",
        key: "temperature",
        colspan: 17,
        children: [
            {
                title: "腹部外科疾病",
                key: "flow",
                colspan: 13,
                children: [
                    { title: "急性胰腺炎", key: "flow1" },
                    { title: "坏死", key: "flow2" },
                    { title: "穿死", key: "flow3" },
                    { title: "胆管炎", key: "flow3" },
                    { title: "肝破裂", key: "flow3" },
                    { title: "脾破裂", key: "flow3" },
                    { title: "胃肠道肿瘤", key: "flow3" },
                    { title: "肠梗阻", key: "flow3" },
                    { title: "腹腔间室综合征", key: "flow3" },
                    { title: "肠系膜动脉拴塞", key: "flow3" },
                    { title: "腹膜后血肿", key: "flow3" },
                    { title: "消化道肿瘤", key: "flow3" },
                    { title: "全腹膜炎", key: "flow3" },
                ],
            },
            {
                title: "消化内科疾病",
                key: "flow",
                colspan: 4,
                children: [
                    { title: "消化道出血", key: "flow1" },
                    { title: "菌群失调", key: "flow2" },
                    { title: "肠道感染", key: "flow3" },
                    { title: "肝功能障碍", key: "flow3" },
                ],
            },
        ],
    },
    {
        title: "泌尿系统疾病",
        key: "temperature",
        colspan: 9,
        children: [
            {
                title: "泌尿外科疾病",
                key: "flow",
                colspan: 5,
                children: [
                    { title: "膀胱破裂", key: "flow1" },
                    { title: "输尿管断裂", key: "flow2" },
                    { title: "肾挫伤", key: "flow3" },
                    { title: "尿道损伤", key: "flow3" },
                    { title: "结石", key: "flow3" },
                ],
            },
            {
                title: "肾内科疾病",
                key: "flow",
                colspan: 4,
                children: [
                    { title: "肾功能不全", key: "flow1" },
                    { title: "尿路感染", key: "flow2" },
                    { title: "肾病综合征", key: "flow3" },
                    { title: "肾炎", key: "flow3" },
                ],
            },
        ],
    },
    {
        title: "血液系统疾病",
        key: "temperature",
        colspan: 6,
        children: [
            {
                title: "血栓病",
                key: "flow",
                colspan: 2,
                children: [
                    { title: "静脉血栓", key: "flow1" },
                    { title: "动脉血栓", key: "flow2" },
                ],
            },
            {
                title: "血液内科疾病",
                key: "flow",
                colspan: 4,
                children: [
                    { title: "DIC", key: "flow1" },
                    { title: "白血病", key: "flow2" },
                    { title: "多发性骨髓瘤", key: "flow3" },
                    { title: "脓毒症", key: "flow3" },
                ],
            },
        ],
    },
    {
        title: "内分泌系统疾病",
        key: "temperature",
        colspan: 6,
        rowspan: 2,
        children: [
            {
                title: "",
                key: "flow",
                colspan: 6,
                children: [
                    {
                        title: "高渗性昏迷",
                        key: "flow",
                    },
                    {
                        title: "糖尿病",
                        key: "flow",
                    },

                    {
                        title: "代谢性脑病",
                        key: "flow",
                    },
                    {
                        title: "低血糖",
                        key: "flow",
                    },
                    {
                        title: "甲亢危象",
                        key: "flow",
                    },
                    {
                        title: "垂体危象",
                        key: "flow",
                    },
                ],
            },
        ],
    },
    {
        title: "循环系统疾病",
        key: "temperature",
        colspan: 10,
        children: [
            {
                title: "休克",
                key: "flow",
                colspan: 7,
                children: [
                    { title: "感染性休克", key: "flow1" },
                    { title: "心源性休克", key: "flow2" },
                    { title: "过敏性休克", key: "flow2" },
                    { title: "失血性休克", key: "flow2" },
                    { title: "低血容量性休克", key: "flow2" },
                    { title: "神经源性休克", key: "flow2" },
                    { title: "梗阻性休克", key: "flow2" },
                ],
            },
            {
                title: "心内科疾病",
                key: "flow",
                colspan: 3,
                children: [
                    { title: "冠心病", key: "flow1" },
                    { title: "心肌梗塞", key: "flow2" },
                    { title: "急性肺水泡", key: "flow3" },
                ],
            },
        ],
    },
    {
        title: "脊柱四肢疾病",
        key: "flow",
        colspan: 3,
        rowspan: 2,
        children: [
            {
                title: "",
                key: "flow1",
                colspan: 3,
                children: [
                    { title: "骨折", key: "flow1" },
                    { title: "脊髓损伤", key: "flow2" },
                    { title: "截瘫", key: "flow3" },
                ],
            },
        ],
    },
    {
        title: "重症产科",
        key: "flow",
        colspan: 7,
        rowspan: 2,
        children: [
            {
                title: "",
                key: "flow1",
                colspan: 7,
                children: [
                    { title: "妊高症", key: "flow1" },
                    { title: "子痫", key: "flow2" },
                    { title: "HELLP综合征", key: "flow3" },
                    { title: "产后大出血", key: "flow3" },
                    { title: "前置胎盘", key: "flow3" },
                    { title: "妊娠性淤胆", key: "flow3" },
                    { title: "国产期心肌病", key: "flow3" },
                ],
            },
        ],
    },
    {
        title: "重症中毒",
        key: "flow",
        colspan: 5,
        rowspan: 2,
        children: [
            {
                title: "",
                key: "flow1",
                colspan: 5,
                children: [
                    { title: "有机磷中毒", key: "flow1" },
                    { title: "百草枯中毒", key: "flow2" },
                    { title: "安眠药中毒", key: "flow3" },
                    { title: "药物中毒", key: "flow3" },
                    { title: "食物中毒", key: "flow3" },
                ],
            },
        ],
    },
    {
        title: "MODS",
        key: "MODS",
        rowspan: 3,
    },
];

const state = reactive({
    // selectedYear: [dayjs().format('YYYY-MM'), dayjs().format('YYYY-MM')],
    selectedYear: [],
    tableData: [],
    loading: false,
    loadingText: '正在加载中...',

});
const { selectedYear, tableData, loading,
    loadingText
} = toRefs(state);
const handleYearChange = (val) => {
    getDiseaseFn()
};
const handleClear = (val) => {
    selectedYear.value = [dayjs().format('YYYY-MM'), dayjs().format('YYYY-MM')]
};

// 导出Excel并选择保存位置
async function exportToExcel(data, fileName = '数据导出.xlsx') {
    const ws = XLSX.utils.json_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([wbout], { type: 'application/octet-stream' });

    if ('showSaveFilePicker' in window) {
        try {
            const fileHandle = await window.showSaveFilePicker({
                suggestedName: fileName,
                types: [{
                    description: 'Excel文件',
                    accept: { 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'] }
                }]
            });
            const writable = await fileHandle.createWritable();
            await writable.write(blob);
            await writable.close();
            return { success: true, message: '文件已成功保存' };
        } catch (error) {
            console.error('保存文件时出错:', error);
            // 继续使用回退下载方式
        }
    }

    // 回退下载方式
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    return { success: true, message: '文件已开始下载' };
}

// 导出
const handleExportExcel = async () => {
    const result = await exportToExcel(tableData.value, `${selectedYear.value[0]}-${selectedYear.value[1]}疾病统计.xlsx`);
    alert(result.message);
};

const printObj = {
    id: "printTable",
    preview: false,
    previewTitle: "打印预览",
    popTitle: "good print",
    minW: "100%",
    maxW: "100%",
    extraHead:
        '<meta http-equiv="Content-Language"content="zh-cn"/><style>@media print { @page { size: landscape; } .print-title { position: running(header); text-align: center; font-size: 22px; font-weight: 600; padding: 10px 0; margin: 0; } @page { @top-center { content: element(header); } } }</style>',
    beforeOpenCallback(vue) {
        console.log("打开之前");
    },
    openCallback(vue) {
        console.log("执行了打印");
    },
    closeCallback(vue) {
        console.log("关闭了打印工具");
    },
};
const fullscreenLoading = ref(false);
// 定义排序数组（按需求顺序）
const sortOrder = [
    "YearMonth",
    "脑出血",
    "脑梗死",
    "蛛网膜下腔出血",
    "脑挫裂伤",
    "弥漫性轴索损伤",
    "脑疝",
    "硬膜下出血",
    "硬膜外出血",
    "颅底骨折",
    "脑脊液耳鼻漏",
    "脑肿瘤",
    "脑血管瘤",
    "癫痫",
    "颅内感染",
    "格林巴利综合征",
    "重症肌无力",
    "肋骨骨折",
    "肺挫伤",
    "胸腔积液",
    "气胸",
    "心包填塞",
    "心脏破裂",
    "气道异物",
    "先心病",
    "风心病",
    "肺癌",
    "食道癌",
    "纵膈肿瘤",
    "肺大泡",
    "脓胸",
    "哮喘",
    "肺炎",
    "AECOPD",
    "肺栓塞",
    "急性喉炎",
    "急性胰腺炎",
    "坏死",
    "穿死",
    "胆管炎",
    "肝破裂",
    "脾破裂",
    "胃肠道肿瘤",
    "肠梗阻",
    "腹腔间室综合征",
    "肠系膜动脉拴塞",
    "腹膜后血肿",
    "消化道肿瘤",
    "全腹膜炎",
    "消化道出血",
    "菌群失调",
    "肠道感染",
    "肝功能障碍",
    "膀胱破裂",
    "输尿管断裂",
    "肾挫伤",
    "尿道损伤",
    "结石",
    "肾功能不全",
    "尿路感染",
    "肾病综合征",
    "肾炎",
    "静脉血栓",
    "动脉血栓",
    "DIC",
    "白血病",
    "多发性骨髓瘤",
    "脓毒症",
    "高渗性昏迷",
    "糖尿病",
    "代谢性脑病",
    "低血糖",
    "甲亢危象",
    "垂体危象",
    "感染性休克",
    "心源性休克",
    "过敏性休克",
    "失血性休克",
    "低血容量性休克",
    "神经源性休克",
    "梗阻性休克",
    "冠心病",
    "心肌梗塞",
    "急性肺水肿",
    "骨折",
    "脊髓损伤",
    "截瘫",
    "妊高症",
    "子痫",
    "HELLP综合征",
    "产后大出血",
    "前置胎盘",
    "妊娠性淤胆",
    "围产期心肌病",
    "有机磷中毒",
    "百草枯中毒",
    "安眠药中毒",
    "药物中毒",
    "食物中毒",
    "MODS",
];

// 排序函数
const sortObjectByOrder = (obj, order) => {
    return order.reduce((acc, key) => {
        if (obj.hasOwnProperty(key)) {
            acc[key] = obj[key];
        }
        return acc;
    }, {});
};

const getDiseaseFn = () => {
    loadingText.value = '正在加载中...'
    loading.value = true

    let date = [
        dayjs(selectedYear.value[0]).startOf('month').format('YYYY-MM-DD'),
        dayjs(selectedYear.value[1]).endOf('month').format('YYYY-MM-DD')
    ]
    getDiseaseAPI(date).then((res) => {
        loading.value = false;
        tableData.value = res.map((item) => {
            return sortObjectByOrder(item, sortOrder)
        });
    }).catch((err) => {
        loading.value = false;
    })
};
defineExpose({
    printObj,
});
</script>

<style scoped>
.table-container {
    width: 100%;
    height: 100%;
    position: relative;
}

.operate {
    display: flex;
}

.complex-table {
    border-collapse: collapse;
    margin: 10px 0;
}

.header {
    background: #0573c2;
    color: white;


}

.header th,
.header td {
    border: 1px solid #13629a;
    padding: 6px;
    text-align: center;
}

tbody th,
tbody td {
    border: 1px solid #aaa9a5;
    padding: 6px;
    text-align: center;
}

.complex-table th {
    font-size: 13px;
}

/* 打印样式 */
@media print {
    body {
        margin: 0;
        padding: 0;
        width: 100vw;
    }

    #printTable {
        width: 100% !important;
        max-width: 100% !important;
        transform-origin: 0 0;
    }

    .complex-table {
        border-right: 2px solid #333;
    }

    .h2 {
        width: 100%;
    }

    td {
        font-size: 9pt;
    }
}
</style>
